import {
  Controller,
  Get,
  Query,
  Param,
  ParseIntPipe,
  Post,
  Body,
  UseGuards,
  Request,
  Delete,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiQuery,
  ApiParam,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { ShortsService } from './shorts.service';
import {
  ShortsListQueryDto,
  ShortsListResponseDto,
  ShortInfoDto,
  ApiShortsListResponseDto,
} from './dto/shorts.dto';

import {
  UpdateWatchProgressDto,
  ApiWatchLogResponseDto,
  BatchDeleteWatchLogsDto,
  ApiBatchDeleteWatchLogsResponseDto,
} from './dto/shorts-watch-log.dto';
import {
  CreateShortsLikeDto,
  ApiShortsLikeResponseDto,
} from './dto/shorts-like.dto';
import {
  CreateShortsFavoriteDto,
  ShortsFavoritesQueryDto,
  BatchDeleteFavoritesDto,
  ApiShortsFavoriteResponseDto,
  ApiShortsFavoritesListResponseDto,
  ApiBatchDeleteFavoritesResponseDto,
} from './dto/shorts-favorite.dto';
import { CreateShortsOrderDto, CreateAdOrderDto } from './dto/shorts-order.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

@ApiTags('短剧')
@Controller('shorts')
export class ShortsController {
  constructor(private readonly shortsService: ShortsService) {}

  @Get()
  @ApiOperation({ summary: '获取短剧列表' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: ApiShortsListResponseDto,
  })
  @ApiQuery({ name: 'page', required: false, description: '页码', example: 1 })
  @ApiQuery({
    name: 'pageSize',
    required: false,
    description: '每页大小',
    example: 20,
  })
  @ApiQuery({ name: 'categoryId', required: false, description: '分类ID' })
  @ApiQuery({ name: 'directionId', required: false, description: '方向ID' })
  @ApiQuery({
    name: 'status',
    required: false,
    description: '短剧状态',
    enum: ['COMPLETED', 'ONGOING'],
  })
  @ApiQuery({ name: 'isFree', required: false, description: '是否免费' })
  @ApiQuery({ name: 'isTop', required: false, description: '是否置顶' })
  @ApiQuery({ name: 'keyword', required: false, description: '搜索关键词' })
  @ApiQuery({
    name: 'sortBy',
    required: false,
    description: '排序方式',
    enum: ['latest', 'popular', 'rating', 'viewCount', 'likeCount'],
  })
  async getShortsList(
    @Query() query: ShortsListQueryDto,
  ): Promise<ShortsListResponseDto> {
    return this.shortsService.getShortsList(query);
  }
  @Get('favorites-all')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户收藏列表' })
  @ApiResponse({ status: 401, description: '未授权' })
  async getUserFavorites(@Request() req) {
    const userId = req.user.id;

    // 不使用分页，查询全部收藏
    return this.shortsService.getUserFavorites(userId);
  }

  @Get('watch-logs')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户观看记录' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiQuery({
    name: 'shortsId',
    required: false,
    description: '短剧ID（可选，不传则获取所有记录）',
  })
  async getUserWatchLogs(@Request() req, @Query('shortsId') shortsId?: string) {
    const userId = req.user.id;
    const shortsIdNum = shortsId ? parseInt(shortsId) : undefined;
    return this.shortsService.getUserWatchLogs(userId, shortsIdNum);
  }
  @Get('random')
  @ApiOperation({ summary: '获取随机短剧' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiQuery({
    name: 'count',
    required: false,
    description: '获取数量',
    example: 5,
  })
  @ApiQuery({
    name: 'categoryId',
    required: false,
    description: '分类ID（可选）',
  })
  @ApiQuery({
    name: 'directionId',
    required: false,
    description: '方向ID（可选）',
  })
  @ApiQuery({
    name: 'isFree',
    required: false,
    description: '是否免费（可选）',
  })
  async getRandomShorts(
    @Request() req,
    @Query('count') count?: string,
    @Query('categoryId') categoryId?: string,
    @Query('directionId') directionId?: string,
    @Query('isFree') isFree?: string,
  ) {
    const params = {
      count: count ? parseInt(count) : 5,
      categoryId: categoryId ? parseInt(categoryId) : undefined,
      directionId: directionId ? parseInt(directionId) : undefined,
      isFree: isFree === 'true' ? true : isFree === 'false' ? false : undefined,
      userId: req.user?.id, // 传递用户ID以检查VIP状态
    };
    return this.shortsService.getRandomShorts(params);
  }

  @Delete('watch-logs/batch')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '批量删除观看记录' })
  @ApiResponse({
    status: 200,
    description: '批量删除成功',
    type: ApiBatchDeleteWatchLogsResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误' })
  @ApiResponse({ status: 401, description: '未授权' })
  async batchDeleteWatchLogs(
    @Request() req,
    @Body() deleteDto: BatchDeleteWatchLogsDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.batchDeleteWatchLogs(userId, deleteDto);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取短剧详情' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: ShortInfoDto,
  })
  @ApiResponse({ status: 400, description: '短剧不存在' })
  @ApiParam({ name: 'id', description: '短剧ID', example: 1 })
  async getShortDetail(
    @Param('id', ParseIntPipe) id: number,
    @Request() req,
  ): Promise<ShortInfoDto> {
    const userId = req.user?.id;
    return this.shortsService.getShortDetail(id, userId);
  }

  @Get('categories/list')
  @ApiOperation({ summary: '获取短剧分类列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getCategories() {
    return this.shortsService.getCategories();
  }

  @Get('directions/list')
  @ApiOperation({ summary: '获取短剧方向列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getDirections() {
    return this.shortsService.getDirections();
  }

  @Post('watch-progress')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新观看进度' })
  @ApiResponse({
    status: 200,
    description: '进度更新成功',
    type: ApiWatchLogResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误或内容不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  async updateWatchProgress(
    @Request() req,
    @Body() watchDto: UpdateWatchProgressDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.updateWatchProgress(userId, watchDto);
  }

  @Post('like')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '点赞/取消点赞短剧' })
  @ApiResponse({
    status: 200,
    description: '操作成功',
    type: ApiShortsLikeResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误或短剧不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  async toggleShortsLike(@Request() req, @Body() likeDto: CreateShortsLikeDto) {
    const userId = req.user.id;
    return this.shortsService.toggleShortsLike(userId, likeDto);
  }

  @Post('favorite')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '收藏/取消收藏短剧' })
  @ApiResponse({
    status: 200,
    description: '操作成功',
    type: ApiShortsFavoriteResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误或短剧不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  async toggleShortsFavorite(
    @Request() req,
    @Body() favoriteDto: CreateShortsFavoriteDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.toggleShortsFavorite(userId, favoriteDto);
  }

  @Delete('favorites/batch')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '批量删除短剧收藏' })
  @ApiResponse({
    status: 200,
    description: '批量删除成功',
    type: ApiBatchDeleteFavoritesResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误' })
  @ApiResponse({ status: 401, description: '未授权' })
  async batchDeleteFavorites(
    @Request() req,
    @Body() deleteDto: BatchDeleteFavoritesDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.batchDeleteFavorites(userId, deleteDto);
  }

  @Get('like/check/:shortsId')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '检查用户是否已点赞短剧' })
  @ApiResponse({ status: 200, description: '检查成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiParam({ name: 'shortsId', description: '短剧ID', example: 1 })
  async checkUserLike(
    @Request() req,
    @Param('shortsId', ParseIntPipe) shortsId: number,
  ) {
    const userId = req.user.id;
    return this.shortsService.checkUserLike(userId, shortsId);
  }

  @Get('favorite/check/:shortsId')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '检查用户是否已收藏短剧' })
  @ApiResponse({ status: 200, description: '检查成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiParam({ name: 'shortsId', description: '短剧ID', example: 1 })
  async checkUserFavorite(
    @Request() req,
    @Param('shortsId', ParseIntPipe) shortsId: number,
  ) {
    const userId = req.user.id;
    return this.shortsService.checkUserFavorite(userId, shortsId);
  }

  @Get('chapter/video/:shortsId/:chapterId')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取章节视频URL（检查订单）' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @ApiResponse({ status: 400, description: '参数错误或内容不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiParam({ name: 'shortsId', description: '短剧ID', example: 1 })
  @ApiParam({ name: 'chapterId', description: '章节ID', example: 1 })
  async getChapterVideo(
    @Request() req,
    @Param('shortsId', ParseIntPipe) shortsId: number,
    @Param('chapterId', ParseIntPipe) chapterId: number,
  ) {
    const userId = req.user.id;
    return this.shortsService.getChapterVideo(userId, shortsId, chapterId);
  }

  @Post('order')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建短剧订单' })
  @ApiResponse({ status: 201, description: '订单创建成功' })
  @ApiResponse({ status: 400, description: '参数错误或内容不存在或已购买' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 403, description: '积分不足' })
  async createShortsOrder(
    @Request() req,
    @Body() createOrderDto: CreateShortsOrderDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.createShortsOrder(userId, createOrderDto);
  }

  @Post('ad-order')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建广告订单' })
  @ApiResponse({ status: 201, description: '广告订单创建成功' })
  @ApiResponse({ status: 400, description: '参数错误或内容不存在或已购买' })
  @ApiResponse({ status: 401, description: '未授权' })
  async createAdOrder(
    @Request() req,
    @Body() createAdOrderDto: CreateAdOrderDto,
  ) {
    const userId = req.user.id;
    return this.shortsService.createAdOrder(userId, createAdOrderDto);
  }
}
